package dujiu.leetcode.slidingWindow.fixed_lengthSlidingWindow;

import java.util.HashSet;
import java.util.Set;

public class P2461 {
    public long maximumSubarraySum(int[] nums, int k) {
        long ans = 0;
        long sum = 0;
        Set<Integer> set = new HashSet<>();
        int left = 0;
        for (int i = 0; i < nums.length; i++) {
            // 进入窗口
            while (set.contains(nums[i])){
                sum -= nums[left];
                set.remove(nums[left]);
                left++;
            }

            // 加入当前元素
            sum += nums[i];
            set.add(nums[i]);
            // 更新答案

            if (set.size() == k) {
                ans = Math.max(sum, ans);
                sum -= nums[left];
                set.remove(nums[left]);
                left++;
            }

        }
        return ans;
    }

    public static void main(String[] args) {
        int[] nums = {9,9,9,1,2,3};
        P2461 p = new P2461();
        System.out.println(p.maximumSubarraySum(nums, 3));
    }
}
